package cn.silver.module.web.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.silver.framework.core.constant.GlobalConstants;
import cn.silver.framework.core.enums.SystemResultEnums;
import cn.silver.framework.core.exception.user.CaptchaException;
import cn.silver.framework.core.exception.user.CaptchaExpireException;
import cn.silver.framework.core.exception.user.UserException;
import cn.silver.framework.core.utils.MessageUtils;
import cn.silver.framework.core.utils.StringUtils;
import cn.silver.framework.core.utils.ValidatorUtils;
import cn.silver.framework.core.validate.auth.PasswordGroup;
import cn.silver.framework.redis.utils.RedisUtils;
import cn.silver.framework.satoken.enums.GrantTypeEnums;
import cn.silver.framework.satoken.model.LoginUser;
import cn.silver.framework.satoken.utils.LoginHelper;
import cn.silver.framework.web.enums.CaptchaTypeEnums;
import cn.silver.module.authority.bean.ClientBean;
import cn.silver.module.system.bean.UserBean;
import cn.silver.module.system.domain.SysUser;
import cn.silver.module.system.enums.UserStatus;
import cn.silver.module.system.service.ISysUserService;
import cn.silver.module.web.enums.LoginType;
import cn.silver.module.web.model.LoginModel;
import cn.silver.module.web.model.LoginPasswordModel;
import cn.silver.module.web.model.LoginResultModel;
import cn.silver.module.web.service.IAuthStrategy;
import cn.silver.module.web.service.SysLoginService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 密码认证策略
 *
 * @author Michelle.Chung
 */
@Slf4j
@Service("password" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class PasswordAuthStrategy implements IAuthStrategy {

    private final ISysUserService userService;
    private final SysLoginService loginService;

    @Override
    public void validate(LoginModel loginModel) {
        LoginPasswordModel model = loginModel.getPassword();
        ValidatorUtils.validate(model, PasswordGroup.class);
    }

    @Override
    public LoginResultModel login(String clientId, LoginModel loginModel, ClientBean client) {
        String tenantId = loginModel.getTenantId();
        LoginPasswordModel model = loginModel.getPassword();
        String username = model.getUsername();
        String password = model.getPassword();
        String code = model.getCode();
        String uuid = model.getUuid();

        UserBean user = loadUserByUsername(tenantId, username);
        boolean captchaEnabled = !CaptchaTypeEnums.NONE.getCode().equalsIgnoreCase(client.getCaptcha());
        // 验证码开关
        if (captchaEnabled) {
            validateCaptcha(tenantId, code, uuid, user, client);
        }

        loginService.checkLogin(LoginType.PASSWORD, tenantId, user, client, () -> !BCrypt.checkpw(password, user.getPassword()));
        // 此处可根据登录用户的数据不同 自行创建 loginUser
        LoginUser loginUser = loginService.buildLoginUser(user);
        loginUser.setDeviceType(client.getDeviceType());
        loginUser.setAuthType(client.getDeviceType());
        SaLoginModel login = new SaLoginModel();
        login.setDevice(client.getDeviceType());
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
        login.setTimeout(client.getTimeout());
        login.setActiveTimeout(client.getActiveTimeout());
        login.setExtra(LoginHelper.CLIENT_KEY, client.getCode());
        login.setExtra(LoginHelper.DEVICE_KEY, client.getDeviceType());
        // 生成token
        LoginHelper.login(loginUser, login);

        loginService.recordLogininfor(GrantTypeEnums.AUTH_PASSWORD.getCode(), loginUser.getTenantId(), user, client,
                SystemResultEnums.SUCCESS.getCode(), MessageUtils.message("user.login.success"));

        LoginResultModel loginResultModel = new LoginResultModel();
        loginResultModel.setAccessToken(StpUtil.getTokenValue());
        loginResultModel.setExpireIn(StpUtil.getTokenTimeout());
        loginResultModel.setClientId(clientId);
        return loginResultModel;
    }

    /**
     * 校验验证码
     *
     * @param tenantId 所属租户
     * @param code     验证码
     * @param uuid     唯一标识
     * @param user     用户信息
     * @param client   客户端信息
     */
    private void validateCaptcha(String tenantId, String code, String uuid, UserBean user, ClientBean client) {
        String verifyKey = Objects.toString(uuid, "");
        String captcha = RedisUtils.getCacheObject(GlobalConstants.CAPTCHA_CODE_KEY, verifyKey);
        RedisUtils.deleteObject(GlobalConstants.CAPTCHA_CODE_KEY, verifyKey);
        if (captcha == null) {
            loginService.recordLogininfor(GrantTypeEnums.AUTH_PASSWORD.getCode(), tenantId, user, client, SystemResultEnums.FAIL.getCode(),
                    MessageUtils.message("user.jcaptcha.expire"));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            loginService.recordLogininfor(GrantTypeEnums.AUTH_PASSWORD.getCode(), tenantId, user, client, SystemResultEnums.FAIL.getCode(),
                    MessageUtils.message("user.jcaptcha.error"));
            throw new CaptchaException();
        }
    }

    private UserBean loadUserByUsername(String tenantId, String username) {
        UserBean user = userService.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getCode, username));
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UserException("user.not.exists", username);
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new UserException("user.blocked", username);
        }
//        if (TenantHelper.isEnable()) {
//            return userMapper.selectTenantUserByUserName(username, tenantId);
//        }
        return user;
    }

}
